/* eslint-disable @typescript-eslint/no-explicit-any */

import router from '@/router/index'
import { defaultRoutes } from '@/router/routes'
import { notFoundRouter } from '@/router/menus'
import type { RouteRecordRaw } from 'vue-router'
import type { IMenuItem } from '@/interface/types/pow/menu.interface'

interface TreeNode {
  [key: string]: any
  children?: TreeNode[]
}

// 注册菜单
function routerPackag(routers: RouteRecordRaw[], parentName?: string) {
  routers.filter((itemRouter: RouteRecordRaw) => {
    // 只有path以/开头的注册
    if (itemRouter.path && itemRouter.path.substring(0, 1) === '/') {
      if (parentName && parentName.length > 0) {
        router.addRoute(parentName, { ...itemRouter })
      } else {
        router.addRoute({ ...itemRouter })
      }
    }
    // 是否存在子集
    // if (itemRouter.children && itemRouter.children.length) {
    //   routerPackag(itemRouter.children, `name_${itemRouter?.meta?.id}`);
    // }
    return true
  })
}

/**
 * 将扁平数组转换为树形结构
 * @param items 扁平数组
 * @param idKey 自定义ID字段名，默认为'id'
 * @param parentIdKey 自定义父ID字段名，默认为'parentId'
 * @param childrenKey 自定义子节点字段名，默认为'children'
 * @returns 树形结构数组
 */
function translateDataToTree<T extends TreeNode>(
  items: T[],
  idKey: string = 'id',
  parentIdKey: string = 'parentId',
  childrenKey: string = 'children',
): T[] {
  // 创建ID到节点的映射
  const itemMap: Record<string | number, T> = {}

  // 初始化所有节点
  items.forEach((item) => {
    itemMap[item.meta[idKey]] = { ...item, [childrenKey]: [] }
  })

  const tree: T[] = []

  items.forEach((item) => {
    const node = itemMap[item.meta[idKey]]
    const parentId = item.meta[parentIdKey]

    if (parentId !== null && parentId !== undefined && itemMap[parentId]) {
      // 如果有父节点，则添加到父节点的children中
      itemMap[parentId][childrenKey].push(node)
    } else {
      // 否则作为根节点
      tree.push(node)
    }
  })

  return tree
}

// 数组按照属性排序
function compare(property: string) {
  return function (a: IMenuItem, b: IMenuItem) {
    const value1 = a[property as keyof IMenuItem] as unknown as number
    const value2 = b[property as keyof IMenuItem] as unknown as number
    return value1 - value2
  }
}

// 菜单初始化
function menuMachining(menus: IMenuItem[]) {
  const arr = menus.sort(compare('orderNum')).map((menu: IMenuItem) => {
    return formatRoutes(menu)
  })
  const menusTree = translateDataToTree(arr, 'id', 'parentId', 'children')

  // 注册菜单
  routerPackag(menusTree)
  routerPackag([notFoundRouter])
  return menusTree
}

// 格式化
function formatRoutes(menu: IMenuItem): RouteRecordRaw {
  return {
    meta: {
      title: menu.title,
      display: Boolean(menu.display),
      isLeaf: menu.isLeaf,
      icon: menu.icon,
      keepAlive: menu.keepAlive,
      id: menu.id,
      parentId: menu.parentId,
    },
    path: menu.path,
    name: `name_${menu.id}`,
    redirect: menu.redirect || '',
    component: defaultRoutes.get(menu.name) || defaultRoutes.get('ErrorDeveloping'),
  }
}

export { menuMachining }
